<template>
  <div class="control-edit">
    <Navbar :bg="navBg" :title="navTitle">
      <template #action>
        <div class="action" @click="onSendClick">完成</div>
      </template>
    </Navbar>
    <div class="date">
      <div class="date-header">
        <div>开始时间</div>
        <div>结束时间</div>
      </div>
      <div class="date-body">
        <div class="start">
          <van-time-picker v-model="startTime" @change="handleStarttimeChange" :show-toolbar="false" />
          <div class="hour">时</div>
          <div class="min">分</div>
        </div>
        <div class="center">
          <van-picker :show-toolbar="false" :columns="columns" />
          <div class="hour">~</div>
        </div>
        <div class="end">
          <van-time-picker v-model="endTime" @change="handleEndtimeChange" :show-toolbar="false" />
          <div class="hour">时</div>
          <div class="min">分</div>
        </div>
      </div>
    </div>
    <div class="week" @click="weekShow = true">
      <div class="title">循环周期</div>
      <div class="description">{{ weekStr }}</div>
      <SvgIcon iconName="s9" color="#D7E5FC" size="10px" />
    </div>
    <div class="control">
      <div class="title">功能控制</div>
      <div class="content">
        <div class="item" v-for="item in r_controlEditItems" :key="item.id" @click="handleCellClick(item)">
          <div class="title">{{ item.title }}</div>
          <template v-if="item.type === 'arrow'">
            <div class="right">
              <div class="value">{{ item.value }}</div>
              <SvgIcon iconName="s9" color="#D7E5FC" size="10px" />
            </div>
          </template>
          <template v-if="item.type === 'switch'">
            <div class="right">
              <van-switch v-model="item.status" size="22px" @change="onCellChange(item, $event)" />
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>

  <!-- 循环周期 -->
  <div class="week-pop">
    <van-popup v-model:show="weekShow" round position="bottom">
      <!-- 自定义弹框内容 -->
      <div class="week-piker">
        <!-- 弹框头部 -->
        <div class="header">
          <div class="cancel" @click="onWeekCancel">取消</div>
          <div class="title">循环周期</div>
          <div class="ok" @click="onWeekConfirm">确定</div>
        </div>
        <!-- 弹框body -->
        <div class="body">
          <div class="item" v-for="item in r_controlWeekItems" :key="item.value">
            <div class="text">{{ item.text }}</div>
            <van-checkbox v-model="item.checked" @change="handleCheckChange(item, $event)"></van-checkbox>
          </div>
        </div>
      </div>
    </van-popup>
  </div>

  <!-- 送风 -->
  <div class="week-pop">
    <van-popup v-model:show="blowingShow" round position="bottom">
      <van-picker
        title="送风"
        confirm-button-text="确定"
        :columns="windColumns"
        @confirm="onBlowingConfirm"
        @cancel="onBlowingCancel"
      />
    </van-popup>
  </div>

  <!-- 排风 -->
  <div class="week-pop">
    <van-popup v-model:show="exhaustShow" round position="bottom">
      <van-picker
        title="排风"
        confirm-button-text="确定"
        :columns="windColumns"
        @confirm="onExhaustConfirm"
        @cancel="onExhaustCancel"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { controlEditItems, weekItems, windItems, controlWeekItems } from '@/utils/enum.js'
import { binaryToHex } from '@/utils/utils.ts'
import Navbar from '@/components/Navbar.vue'
import { sendToNative_sendUartData } from '@/utils/base.js'
import { verifySum } from '@/utils/utils.ts'

import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
console.log('当前路由信息:', route)
let sendSetData = ref(new Array(11).fill(0)) // 先设置一个含有 11 个元素的空数据，用于保存程控设置的下发命令，数据下发格式参考协议
const controlIdx = ref('01') // 当前操作的控件索引

// 访问参数
const routeQuery = JSON.parse(route.query.item)
console.log('访问参数:', routeQuery)
// let controlInfo = ref({})
controlIdx.value = `0${route.query.index}`
sendSetData.value[0] = controlIdx.value

const navBg = ref('#fff')
const navTitle = ref('第一组')
const startTime = ref(['00', '00'])
const endTime = ref(['00', '00'])
const weekStr = ref('')

const weekShow = ref(false) // 循环周期
const exhaustShow = ref(false) // 排风
const blowingShow = ref(false) // 送风

const columns = reactive(weekItems)
const windColumns = reactive(windItems)
const r_controlEditItems = ref(controlEditItems)
const r_controlWeekItems = ref(controlWeekItems)

let weekBits = ref(new Array(8).fill(0)) // 先设置一个含有 7 个元素的空数据，用于保存星期几的设置，
console.log('sendSetData:', sendSetData)

// 初始化（页面）
console.log('页面初始化')
r_controlEditItems.value[0].value = windColumns[routeQuery.blowing].text
r_controlEditItems.value[1].value = windColumns[routeQuery.exhaust].text
r_controlEditItems.value[2].status = routeQuery.pdp ? true : false
r_controlEditItems.value[3].status = routeQuery.anion ? true : false

startTime.value[0] = routeQuery.startHour
startTime.value[1] = routeQuery.startMin
endTime.value[0] = routeQuery.endHour
endTime.value[1] = routeQuery.endMin
// 处理星期数据
weekStr.value = routeQuery.weekStr
weekBits.value = routeQuery.week.split('').map(Number)
console.log('weekBits:', weekBits.value)

// 初始化（数据）
const iniPageData = (params: any, idx: string) => {
  console.log('iniPageData:', params)
  console.log('idx:', idx)
  // 此时从路由传过来的数据是 10 进制，需要转换为 16 进制
  sendSetData.value[0] = idx
  // 星期 '01111111'
  sendSetData.value[1] = binaryToHex(params.week)
  // 开始时
  sendSetData.value[2] = params.startHour.toString(16).padStart(2, '0')
  // 开始分
  sendSetData.value[3] = params.startMin.toString(16).padStart(2, '0')
  // 结束时
  sendSetData.value[4] = params.endHour.toString(16).padStart(2, '0')
  // 结束分
  sendSetData.value[5] = params.endMin.toString(16).padStart(2, '0')
  // 等离子
  sendSetData.value[6] = params.pdp.toString(16).padStart(2, '0')
  // 负离子
  sendSetData.value[7] = params.anion.toString(16).padStart(2, '0')
  // 排风
  sendSetData.value[8] = params.exhaust.toString(16).padStart(2, '0')
  // 送风
  sendSetData.value[9] = params.blowing.toString(16).padStart(2, '0')

  console.log('页面初始化保存的数据sendSetData:', sendSetData.value)
}

iniPageData(routeQuery, controlIdx.value)

/**
 * @description 处理星期数据
 * @param bit eg: '00001001'
 * @returns 返回 controlWeekItems的checked属性是否是选中的
 */
const bitToWeek = (bit: string) => {
  console.log('bitToWeek:', bit)
  // 先将bit倒序
  const arr = bit.split('').reverse()
  console.log('arr:', arr)
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === '1') {
      r_controlWeekItems.value[i].checked = true
    }
  }
}

bitToWeek(routeQuery.week)

watch(
  () => routeQuery.value,
  (val: any) => {
    console.log('路由数据变化了==', val)
  },
  { deep: true }
)
// 完成编辑，此处下发该编辑页面所有选项数据
const onSendClick = () => {
  console.log('提交的数据sendSetData', sendSetData.value)
  const data = sendSetData.value.join('')
  const sum = verifySum(`020E00340B${data}`)
  const hexUart = `F1F1020E00340B${data}${sum}7E`
  console.log('hexUart:', hexUart)
  sendToNative_sendUartData(hexUart)
  router.go(-1)
}

const onWeekConfirm = () => {
  onWeekCancel()
}
// 送风确认
const onBlowingConfirm = ({ selectedOptions }: any) => {
  console.log(selectedOptions, 'selectedOptions')
  const { text, value } = selectedOptions[0]
  console.log(text)
  console.log(value)
  r_controlEditItems.value[0].value = text
  sendSetData.value[10] = `0${value}`
  onBlowingCancel()
}
// 排风确认
const onExhaustConfirm = ({ selectedOptions }: any) => {
  console.log(selectedOptions, 'selectedOptions')
  const { text, value } = selectedOptions[0]
  console.log(text)
  console.log(value)
  r_controlEditItems.value[1].value = text
  sendSetData.value[9] = `0${value}`
  onExhaustCancel()
}
const onWeekCancel = () => {
  weekShow.value = false
}
const onExhaustCancel = () => {
  exhaustShow.value = false
}
const onBlowingCancel = () => {
  blowingShow.value = false
}

const handleCellClick = (item: any) => {
  const { id } = item
  if (id === 1) {
    // 送风
    blowingShow.value = true
  } else if (id === 2) {
    // 排风
    exhaustShow.value = true
  }
}

// 等离子 负离子的数据变量监听
const onCellChange = (val: any, e: any) => {
  console.log(val, 'val')
  console.log(e, 'e')
  const { id } = val
  if (id === 3) {
    // 等离子
    sendSetData.value[7] = e ? '01' : '00'
  } else if (id === 4) {
    // 负离子
    sendSetData.value[8] = e ? '01' : '00'
  }
}
// 星期选中事件处理
const handleCheckChange = (val: any, e: any) => {
  console.log(val, 'val')
  console.log(e, 'e')
  const { value } = val
  weekBits.value[value] = e ? 1 : 0
  console.log(weekBits.value, 'weekBits')
  sendSetData.value[2] = binaryToHex(weekBits.value.join(''))
}

const handleStarttimeChange = ({ selectedValues }: any) => {
  console.log(selectedValues, 'selectedValues')
  sendSetData.value[3] = Number(selectedValues[0]).toString(16).padStart(2, '0')
  sendSetData.value[4] = Number(selectedValues[1]).toString(16).padStart(2, '0')
  console.log(sendSetData.value, 'handleStarttimeChange')
}
const handleEndtimeChange = ({ selectedValues }: any) => {
  console.log(selectedValues, 'selectedValues')
  sendSetData.value[5] = selectedValues[0].toString(16).padStart(2, '0')
  sendSetData.value[6] = selectedValues[1].toString(16).padStart(2, '0')
}
</script>
<style lang="less" scoped>
@import url(../assets/style/control-edit.less);
</style>
